package com.system.blogAdmin.auth.controller;


import com.cnc.common.web.util.MessageBox;
import com.cnc.common.web.util.SpringValidUtil;
import com.system.blogAdmin.auth.dto.AuthRoleDto;
import com.system.blogAdmin.auth.dto.TreeDto;
import com.system.blogAdmin.auth.dto.UploadDto;
import com.system.blogAdmin.auth.dto.UserDto;
import com.system.blogAdmin.auth.entity.AuthResource;
import com.system.blogAdmin.auth.entity.AuthRole;
import com.system.blogAdmin.auth.entity.User;
import com.system.blogAdmin.auth.kit.ShiroKit;
import com.system.blogAdmin.auth.service.AuthResourceService;
import com.system.blogAdmin.auth.service.AuthRoleService;
import com.system.blogAdmin.auth.service.AuthUserRoleService;
import com.system.blogAdmin.auth.service.UserService;
import com.system.blogAdmin.utils.DtoUtils;
import com.system.blogAdmin.utils.Properties;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者： Administrator
 * 创建时间：2017-04-20.
 * 版本：1.0
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    AuthResourceService authResourceService;
    @Autowired
    AuthRoleService authRoleService;
    @Autowired
    AuthUserRoleService authUserRoleService;


    @RequestMapping(value = "/index",method = RequestMethod.GET,produces="application/json;charset=UTF-8")
    public String index(){
        return "blogAdmin/auth/user_manager";
    }

    @RequestMapping(value = "/userInfo",method = RequestMethod.GET,produces="application/json;charset=UTF-8")
    public String userInfo(){
        return "blogAdmin/auth/user_info";
    }

    @RequestMapping(value = "/list/menu/{userId}",method = RequestMethod.POST,produces="application/json;charset=UTF-8")
    @ResponseBody
    public List<AuthResource> getMenu(@PathVariable long userId) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //超级管理员
        if(user.getAccount().equals(User.ADMIN_USER_NAME)){
            List<AuthResource> authResources = authResourceService.authResourceList(AuthResource.MENU_RESOURCE);
            return  authResources;
        }else {
            List<AuthResource> list = new ArrayList<AuthResource>();
            List<AuthResource> resourceslist = authResourceService.listResourseByUserId(userId);
            if (resourceslist != null && resourceslist.size() > 0){
                for (AuthResource resource : resourceslist) {
                    if (resource.getType().equals(AuthResource.MENU_RESOURCE)) {
                        list.add(resource);
                    }
                }
            }
            return  list;
        }
    }

    @RequestMapping(value = "/list",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<UserDto> userList (){
        return userService.getAllUser();
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public MessageBox addUser (@Valid User user,BindingResult result){
        //验证所传参数是否有误,如有错自动装载错误消息回去
        if(result.hasErrors()){
            return MessageBox.getErrorMsg(Properties.insertFailed + SpringValidUtil.getErrors2Str(result));
        }
        userService.insertUser(user);
        return MessageBox.getSuccessMsg(Properties.insertSuccess);
    }

    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public MessageBox deleteUser (@PathVariable Long id){
        userService.deleteById(id);
        return MessageBox.getSuccessMsg(Properties.deleteSuccess);
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public MessageBox modifyUser (@Valid User user, BindingResult result){
        if(result.hasErrors()){
            String erorStr = SpringValidUtil.getErrors2Str(result);
            return  MessageBox.getErrorMsg(Properties.updateFailed +erorStr);
        }
        if(!user.getPassword().equals("")||user.getPassword().trim().length()>0){
            user.setPassword(ShiroKit.md5(user.getPassword(), user.getAccount() + user.getPassword()));
            userService.update(user);
        }
        return MessageBox.getSuccessMsg(Properties.updateSuccess);
    }


    /**
     * 获取用户id所拥有资源
     * @param id
     * @return
     */
    @RequestMapping(value = "/userResource/{id}",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public  List<TreeDto> getResourceByUserId(@PathVariable Long id){
        return DtoUtils.res2treeDto(authResourceService.listResourseByUserId(id));
    }

    /**
     * 获取所拥有用户
     * @param id
     * @return
     */
    @RequestMapping(value = "/userRoleResource/{id}",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<AuthRole> getAuthRoleByUserId(@PathVariable Long id){
        return authRoleService.getAuthRoleByUserId(id);
    }

    /**
     * 根据用户 ID 获取 角色
     * @param id
     * @return
     */
    @RequestMapping(value = "/getUserRole/{id}",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public List<AuthRoleDto> getPermission(@PathVariable Long id){
        List<AuthRole> authRoleList =  authRoleService.getAuthRoleByUserId(id);
        List<AuthRole> authRoleList2 = authRoleService.listAuthRole();
        return DtoUtils.roles2roleDto(authRoleList2, authRoleList);
    }

    /**
     * 设置用户角色权限
     * @param userList
     * @param userId
     * @return
     */
    @RequestMapping(value = "/setUserRolePermission", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public MessageBox setPermission(@RequestParam(value="userList[]",required = false)List<Long> userList, Long userId){
            authUserRoleService.setUserRole(userList, userId);
            return MessageBox.getSuccessMsg(Properties.updateSuccess);
    }


    /**
     * 上传头像
     * @param image
     * @return
     */
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public UploadDto setUserImg(@RequestParam (value = "image",required = false)String image){
        UploadDto uploadDto = new UploadDto();
        User user = new User();
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            User u = (User) subject.getPrincipal();
            user.setId(u.getId());
            user.setUserImg(image);
            userService.update(user);
            uploadDto.setType("success");
            uploadDto.setResult(Properties.updateSuccess);
            uploadDto.setFile(image);
            return uploadDto;
        }
        uploadDto.setType("error");
        uploadDto.setResult(Properties.updateFailed);
        return uploadDto;
    }
}
